// import 'preact/devtools';
// import 'preact/debug';
import { render, h, Fragment } from 'preact';
import { map } from 'lodash-es';

import { setupModel } from './model';
import History from './history/History';
import Graph from './vm/Graph';
import BaseNode from './vm/BaseNode';
import RectNode from './vm/RectNode';
import { setComponent } from './vm/observerComponents';
import { registerModel } from './model/index';

class LogicFlow {
  domRef = null;
  graphModel = null;
  history = new History();

  constructor({ domRef }) {
    this.domRef = domRef;
  }

  render(graphData) {
    const { graphModel } = setupModel(graphData);
    this.graphModel = graphModel;

    this.history.watch(this.graphModel);

    render((
      <>
        <Graph graphModel={this.graphModel} />
      </>
    ), this.domRef);
  }

  registerNode(type, fn) {
    const { customNode, customModel } = fn({
      BaseNode,
      RectNode,
      h
    })
    setComponent(type, customNode);
    registerModel(type, customModel);
  }

  undo() {
    if (!this.history.undoAble()) return;
    const graphData = this.history.undo();
    this.render(graphData);
  }

  redo() {
    if (!this.history.redoAble()) return;
    const graphData = this.history.redo();
    this.render(graphData);
  }
}

export default LogicFlow;


// 以下为 DEBUG 相关的代码
const lf = new LogicFlow({
  domRef: document.getElementById('container')
});
window.lf = lf;

const uodoBtn = document.getElementById('undo-button');
uodoBtn.addEventListener('click', () => {
  lf.undo();
}, false);

const redoBtn = document.getElementById('redo-button');
redoBtn.addEventListener('click', () => {
  lf.redo();
}, false);
